package com.miya.order.configure.rabbitmq.dead;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 业务侦听器
 *
 * @author Caixiaowei
 * @date 2022/02/21
 */
@Slf4j
@Component
public class BusinessListener {

	@RabbitListener(queues = DeadLetterDemoConfigure.BUSINESS_QUEUEA)
	public void receiveA(Message message, Channel channel) throws IOException {
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		boolean ack = true;
		Exception exception = null;
		try {
			String messageStr = new String(message.getBody(), StandardCharsets.UTF_8);
			log.info("receiveA mq通知，消息体：【{}】", messageStr);
			// TODO 具体业务

			if (messageStr.contains("deadLetter")) {
				throw new RuntimeException("dead letter exception");
			}
			channel.basicAck(deliveryTag, false);
		} catch (Exception ex) {
			ack = false;
			exception = ex;
		}
		if (!ack) {
			log.error("receiveA 消费异常, error msg: {}", exception.getMessage());
			channel.basicNack(deliveryTag, false, false);
		}
	}
}
